<template>
  <div class="progress box clmcenter">
    <p class="progressbar">加载中...{{ percent }}</p>
  </div>
</template>

<script>
import { Toast } from "vant";
export default {
  name: "LoadingPage",
  data() {
    return {
      count: 0,
      percent: "",
    };
  },
  mounted() {
    this.preload();
  },
  methods: {
    getUserStatus() {
      let code = this.getQueryVariable("code");
      Toast.loading({
        message: "loading...",
        forbidClick: true,
        duration: 0, //值为 0 时，toast 不会消失
        overlay: true, //是否显示背景遮罩层
      });
      //获取用户状态
      this.$http.post("/index", { code }).then((res) => {
        Toast.clear();
        if (res.data.code == 200) {
          this.$store.commit("setImgInfo", res.data.data);
          this.$router.replace("/index");
        } else {
          Toast(res.data.msg);
        }
      });
    },
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === variable) {
          return pair[1];
        }
      }
      return false;
    },
    preload() {
      let chooseEat = require.context("../assets/img", false, /\.jpg|png$/);
      let song = require.context("../assets/img/song", false, /\.jpg|png$/);
      // 文件夹图片
      let chooseEatList = [];
      let songList = [];
      // 总数据
      let allList = [];
      for (let i = 0; i < chooseEat.keys().length; i++) {
        chooseEatList.push({
          id: 1,
          img: chooseEat.keys()[i].substr(2, chooseEat.keys()[i].length),
        });
      }
      for (let i = 0; i < song.keys().length; i++) {
        songList.push({
          id: 1,
          img: song.keys()[i].substr(2, song.keys()[i].length),
        });
      }
      allList = chooseEatList.concat(songList);
      // 合并数据
      // 根据层级追加目录路径前缀 1chooseEat 2end 3home 4lamp
      this.allList = allList;
      for (var b in allList) {
        var image = new Image();
        if (allList[b].id === 1) {
          image.src = require("../assets/img/" + allList[b].img);
        }
        if (allList[b].id === 2) {
          image.src = require("../assets/img/song/" + allList[b].img);
        }
        // 图片加载
        image.onload = () => {
          this.count++;
          // 计算图片加载的百分数，绑定到percent变量
          let percentNum = Math.floor((this.count / this.allList.length) * 100);
          this.percent = `${percentNum}%`;
        };
      }
    },
  },

  watch: {
    count: function (val) {
      // console.log(val);
      if (val === 19) {
        // 图片加载完成后
        this.getUserStatus();
        // this.$router.replace('/index')
      }
    },
  },
};
</script>
<style lang="less" scoped>
.progress {
  p {
    font-size: 2rem;
    padding-top: 1rem;
  }
}
</style>
